package org.cht.webapp.action;

import com.opensymphony.xwork2.Preparable;
import org.cht.service.GenericManager;
import org.cht.model.PipeLine;
import org.cht.webapp.action.BaseAction;

import java.util.List;

public class PipeLineAction extends BaseAction implements Preparable {
    private GenericManager<PipeLine, Long> pipeLineManager;
    private List pipeLines;
    private PipeLine pipeLine;
    private Long  id;

    public void setPipeLineManager(GenericManager<PipeLine, Long> pipeLineManager) {
        this.pipeLineManager = pipeLineManager;
    }

    public List getPipeLines() {
        return pipeLines;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String pipeLineId = getRequest().getParameter("pipeLine.id");
            if (pipeLineId != null && !pipeLineId.equals("")) {
                pipeLine = pipeLineManager.get(new Long(pipeLineId));
            }
        }
    }

    public String list() {
        pipeLines = pipeLineManager.getAll();
        return SUCCESS;
    }

    public void setId(Long  id) {
        this. id =  id;
    }

    public PipeLine getPipeLine() {
        return pipeLine;
    }

    public void setPipeLine(PipeLine pipeLine) {
        this.pipeLine = pipeLine;
    }

    public String delete() {
        pipeLineManager.remove(pipeLine.getId());
        saveMessage(getText("pipeLine.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            pipeLine = pipeLineManager.get(id);
        } else {
            pipeLine = new PipeLine();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (pipeLine.getId() == null);

        pipeLineManager.save(pipeLine);

        String key = (isNew) ? "pipeLine.added" : "pipeLine.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}